package com.example.demo.thread.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author: htc
 * @date: Created in 16:51 2019/1/2.
 */
public class TraditionalTimer {
    static int count = 0;

    public static void main(String[] args) {
//        demo1();
        demo2();
    }

    /**
     * 基本定时器
     */
    public static void demo1() {
        //10s后启动，每3s运行一次
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("bombing!");
            }
        }, 10000, 3000);

        while (true) {
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 嵌套定时器
     */
    public static void demo2() {
        class MyTimerTask extends TimerTask {

            @Override
            public void run() {
                count = (count + 1) % 2;
                System.out.println("bombing!");
                new Timer().schedule(/*new TimerTask() {
                    @Override
                    public void run() {
                        System.out.println("bombing!");
                    }
                }*/new MyTimerTask(), 2000 + 2000 * count);
            }
        }

        //10s后启动，每2s运行一次，然后每4s运行一次，然后再每2s运行一次，然后每4s运行一次，如此往复
        new Timer().schedule(new MyTimerTask(), 2000);

        while (true) {
            System.out.println(new Date().getSeconds());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *
     */
    public static void demo3(){

    }
}
